package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.OilyProduct;
import com.apes.autoparts.product.model.WiperProduct;
import com.apes.autoparts.product.repository.OilyProductRepository;
import com.apes.autoparts.product.repository.WiperProductRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @ClassName OilyProductService
 * @Description 描述
 * @Author wushilong
 * @Date 2022/10/26 17:47
 * @Version 1.0
 */
@Service
public class WiperProductService extends DomainService {

    @Autowired
    private WiperProductRepository wiperProductRepository;

    /**
     * 批量更新、新增、删除
     *
     * @param request
     * @return
     */
    public Map edit(SimpleRequest request) {
        //新增和修改
        List<WiperProduct> wiperProducts = request.getA("wiperProductItems", WiperProduct.class);
        Set<String> wiperPrioritySet = new HashSet<>();

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))) {
            List<WiperProduct> delWiperProducts = request.getA("del", WiperProduct.class);
            delWiperProducts.forEach(wiperProduct -> {
                String sole = wiperProduct.getBrand() + wiperProduct.getName() + wiperProduct.getUnit() + wiperProduct.getFramework();
                if (Objects.nonNull(wiperProduct.getId()) && wiperPrioritySet.add(sole)) {
                    wiperProductRepository.delete(wiperProduct);
                }
            });
        }

        //保存并返回
        List<WiperProduct> resultWiperProduct;
        try {
            resultWiperProduct =
                    wiperProducts.stream().map(wiperProduct -> wiperProductRepository.saveAndFlush(wiperProduct))
                            .collect(Collectors.toList());
        } catch (RuntimeException e) {
            if (e.getMessage().contains("ORA-00001")) throw new RuntimeException("请勿添加重复数据，请检查添加数据是否正确！");
            throw new RuntimeException(e);
        }

        return MapUtil.mapper("wiperProductItems", resultWiperProduct);
    }

    /**
     * 定制导入品牌标准商品
     *
     * @param request
     */
    public JSONObject importWiperProduct(SimpleRequest request) {
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     *
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {

        AtomicReference<String> key = new AtomicReference<>();

        JSONArray titleArray = new JSONArray(12);
        titleArray.add("序号");
        titleArray.add("编号");
        titleArray.add("品牌");
        titleArray.add("零件名称");
        titleArray.add("单位");
        titleArray.add("型号");
        titleArray.add("雨刮尺寸[寸]");
        titleArray.add("接口类型");
        titleArray.add("架构");
        titleArray.add("系列");
        titleArray.add("产品描述");
        titleArray.add("条形码");
        titleColumnArray.add(titleArray);

        List dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            importDataValueArray.parallelStream().forEach(item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() == 0) return;

                String brand = "";
                String name = "";
                String unit = "";
                String model = "";
                String wiperSize = "";
                String apiClass = "";
                String framework = "";
                String catena = "";
                String description = "";
                String barCode = "";

                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0: brand = iValueArray.getString(0);
                            break;
                        case 1: name = iValueArray.getString(1);
                            break;
                        case 2: unit = iValueArray.getString(2);
                            break;
                        case 3: model = iValueArray.getString(3);
                            break;
                        case 4: wiperSize = iValueArray.getString(4);
                            break;
                        case 5: apiClass = iValueArray.getString(5);
                            break;
                        case 6: framework = iValueArray.getString(6);
                            break;
                        case 7: catena = iValueArray.getString(7);
                            break;
                        case 8: description = iValueArray.getString(8);
                            break;
                        case 9: barCode = iValueArray.getString(9);
                            break;
                    }
                }
                //跳过首行标题行
                if ("品牌".equals(brand) || "零件名称".equals(name)) return;

                Map<String, String> oilyProduct = wiperProductRepository.queryByCondition(brand, name, unit, model);

                JSONArray newDataArray = new JSONArray(12);
                newDataArray.add(0);
                newDataArray.add(oilyProduct.size() == 0 ? "" : oilyProduct.get("id"));
                newDataArray.add(brand);
                newDataArray.add(name);
                newDataArray.add(unit);
                newDataArray.add(model);
                newDataArray.add(wiperSize);
                newDataArray.add(apiClass);
                newDataArray.add(framework);
                newDataArray.add(catena);
                newDataArray.add(description);
                newDataArray.add(barCode);

                dataList.add(MapUtil.mapped(newDataArray));
            });
        });

        titleColumnArray.addAll(dataList);
        return key.get();
    }

    /**
     * 放弃编辑回显当前数据
     *
     * @param request
     * @return
     */
    public Map wiperProductFindOne(SimpleRequest request) {
        List<WiperProduct> list = request.getA("wiperProductItems", WiperProduct.class);
        return MapUtil.mapper("wiperProductItems", list);
    }


    /**
     * 动态条件查询
     * @param request
     */
    public List<WiperProduct> conditionQuery(SimpleRequest request){
        JSONObject jo = request.getJO();

        String brand = jo.getString("brand");
        String name = jo.getString("name");
        String unit = jo.getString("unit");
        String model = jo.getString("model");
        String wiperSize = jo.getString("wiperSize");
        String apiClass = jo.getString("apiClass");
        String framework = jo.getString("framework");
        String catena = jo.getString("catena");

        if ("".equals(brand)) brand = null;
        if ("".equals(name)) name = null;
        if ("".equals(unit)) unit = null;
        if ("".equals(model)) model = null;
        if ("".equals(wiperSize)) wiperSize = null;
        if ("".equals(apiClass)) apiClass = null;
        if ("".equals(framework)) framework = null;
        if ("".equals(catena)) catena = null;

        return wiperProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("name", "EQ", name,
                "brand", "EQ", brand,
                "unit", "EQ", unit,
                "model", "EQ", model,
                "wiperSize", "EQ", wiperSize,
                "apiClass", "EQ", apiClass,
                "framework", "EQ", framework,
                "catena", "EQ", catena));
    }
}
